package ysq.xyg.web.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import ysq.xyg.base.model.dto.ReturnEntity;
import ysq.xyg.base.service.impl.BaseServiceImpl;
import ysq.xyg.base.util.BaseConstant;
import ysq.xyg.base.util.BaseUtil;
import ysq.xyg.sys.model.po.SysUser;
import ysq.xyg.web.dao.WebWithdrawDao;
import ysq.xyg.web.model.po.WebMember;
import ysq.xyg.web.model.po.WebScoreRecord;
import ysq.xyg.web.model.po.WebWithdraw;
import ysq.xyg.web.model.vo.WebWithdrawVo;
import ysq.xyg.web.service.WebMemberService;
import ysq.xyg.web.service.WebScoreRecordService;
import ysq.xyg.web.service.WebWithdrawService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


/**
 * 商城模块-提现表service实现
 *
 * @author congcong tao
 * @date 2019-4-28 11:19:58
 */
@Service("webWithdrawService")
public class WebWithdrawServiceImpl extends BaseServiceImpl<WebWithdraw> implements WebWithdrawService {

    @Autowired
    private WebMemberService webMemberService;
    @Autowired
    private WebScoreRecordService webScoreRecordService;
    @Resource
    private WebWithdrawDao webWithdrawDao;

    @Autowired
    public void setBaseDao(WebWithdrawDao webWithdrawDao) {
        this.baseDao = webWithdrawDao;
    }

    /**
     * 分页查询
     *
     * @param WebWithdrawVo 对象
     * @param pageSize 展示数量
     * @param pageNum 当前页面
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-4-28 11:19:58
     */
    @Override
    public ReturnEntity page(WebWithdrawVo WebWithdrawVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" update_time desc");
        List<WebWithdraw> list = acceptList(WebWithdrawVo);
        PageInfo<WebWithdraw> page=new PageInfo<WebWithdraw>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    @Override
    public ReturnEntity pageLeft(WebWithdrawVo WebWithdrawVo, int pageSize, int pageNum) {
        if (StringUtils.isNotEmpty(WebWithdrawVo.getMemberNickName())) {
            WebWithdrawVo.setMemberNickName(BaseUtil.encodeBase64String(WebWithdrawVo.getMemberNickName()));
        }
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" update_time desc");
        List<WebWithdraw> list = webWithdrawDao.selectEntityList(WebWithdrawVo);
        // nickName
        if (list != null && list.size() > 0) {
            for (WebWithdraw WebWithdraw : list) {
                if (StringUtil.isNotEmpty(WebWithdraw.getMemberNickName())) {
                    WebWithdraw.setMemberNickName(BaseUtil.decodeBase64(WebWithdraw.getMemberNickName()));
                }
                if (WebWithdraw.getCreateTime() != null) {
                    WebWithdraw.setCreateTimeStr(DateUtil.formatDateTime(WebWithdraw.getCreateTime()));
                }
            }
        }
        PageInfo<WebWithdraw> page=new PageInfo<WebWithdraw>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    /**
     * 修改
     *
     * @param webWithdrawVo 对象
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-4-28 11:19:58
     */
    @Override
    public ReturnEntity addOrUpdate(WebWithdrawVo webWithdrawVo, SysUser currentUser) {
        boolean isUpate=true;
        WebWithdraw webWithdraw;
        if(StrUtil.isEmpty(webWithdrawVo.getId())){
            webWithdraw=new WebWithdraw(currentUser);
            isUpate=false;
        }else{
            webWithdraw=selectByPrimaryKey(webWithdrawVo.getId());
            if(ObjectUtil.isNull(webWithdraw)){
                return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
            }
            webWithdraw.setUpdateTime(new Date());
            webWithdraw.setUpdateUser(currentUser.getId());
        }
        webWithdraw.setMemberId(webWithdrawVo.getMemberId());
        webWithdraw.setMoney(webWithdrawVo.getMoney());
        webWithdraw.setAlipay(webWithdrawVo.getAlipay());
        webWithdraw.setBankCard(webWithdrawVo.getBankCard());
        webWithdraw.setStatus(webWithdrawVo.getStatus());
        webWithdraw.setManageStatus(webWithdrawVo.getManageStatus());
        webWithdraw.setDescription(webWithdrawVo.getDescription());
        webWithdraw.setApplyTime(webWithdrawVo.getApplyTime());
        webWithdraw.setManageTime(webWithdrawVo.getManageTime());
        int num=0;
        if(isUpate){
            num=updateByPrimaryKey(webWithdraw);
        }else{
            num=insert(webWithdraw);
        }
        if(num<=0){
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        return new ReturnEntity();
    }
    /**
     * 删除
     *
     * @param id 主键id
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-4-28 11:19:58
     */
    @Override
    public ReturnEntity delete(String id, SysUser currentUser) {
        WebWithdraw webWithdraw=selectByPrimaryKey(id);
        if(webWithdraw!=null){
            webWithdraw.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_DELETE);
            webWithdraw.setUpdateTime(new Date());
            webWithdraw.setUpdateUser(currentUser.getId());
            int num=updateByPrimaryKey(webWithdraw);
            if(num>0){
                return new ReturnEntity();
            }
        }
        return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
    }

    /**
     * 获取集合
     *
     * @param webWithdrawVo 对象
     * @return List<BaseDict> BaseDict集合
     * @author congcong tao
     * @date 2019-4-28 11:19:58
     */
    @Override
    public List<WebWithdraw> acceptList(WebWithdrawVo webWithdrawVo){
        Example example = new Example(WebWithdraw.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtil.isNotEmpty(webWithdrawVo.getRemoveTag())){
            criteria.andEqualTo("removeTag",webWithdrawVo.getRemoveTag());
        }
        example.setOrderByClause(" update_time desc");
        return webWithdrawDao.selectByExample(example);
    }

    @Override
    public List<WebWithdraw> selectEntityList(WebWithdrawVo WebWithdrawVo) {
        return webWithdrawDao.selectEntityList(WebWithdrawVo);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity withdrawEdit(WebMember webMember, String money) {
        if (StringUtils.isEmpty(money)) {
            return new ReturnEntity(BaseConstant.FAIL, "提现金额不能为空");
        }
        Double d = Double.parseDouble(money);
        Double memberMoney = webMember.getMoney();
        if (memberMoney == null) {
            memberMoney = 0.0;
        }
        if (d > memberMoney) {
            return new ReturnEntity(BaseConstant.FAIL, "提现金额不足，无法提现");
        }
        String id = BaseUtil.uId();
        WebWithdraw withdraw = new WebWithdraw();
        withdraw.setId(id);
        withdraw.setAccountId(webMember.getAccountId());
        withdraw.setMemberId(webMember.getId());
        // money就是积分
        withdraw.setMoney(money);
        withdraw.setStatus(BaseConstant.RECOVERY_WASTE_MEMBER_STATUS_ONE);
        withdraw.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
        withdraw.setCreateTime(new Date());
        int flag = this.insert(withdraw);
        if(flag <= 0){
            return new ReturnEntity(BaseConstant.FAIL, BaseConstant.DO_FAIL);
        }
        // 需要修改自身金额
        if (webMember != null && StringUtils.isNotEmpty(money)) {
            // 减去积分
            // 需要计算总金额，并提交到webMember中
            webMember.setNickName(null);
            webMember.setMoney(memberMoney - d);
            webMemberService.updateByPrimaryKeySelective(webMember);
            // 增加记录
            /*WebScoreRecord webScoreRecord = new WebScoreRecord();
            webScoreRecord.setId(BaseUtil.uId());
            webScoreRecord.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
            webScoreRecord.setCreateTime(new Date());
            webScoreRecord.setUpdateTime(webScoreRecord.getCreateTime());
            webScoreRecord.setScore(money);
            webScoreRecord.setExtraId(withdraw.getId());
            webScoreRecord.setRecordType("2");
            webScoreRecord.setMemberId(withdraw.getMemberId());
            webScoreRecord.setDescripts("用户提现成功，增加积分");
            webScoreRecordService.insert(webScoreRecord);*/
            return new ReturnEntity();
        }
        return new ReturnEntity();
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity updateStatus(String id, String type, String status, String description) {
        if(StringUtil.isEmpty(id)){
            return new ReturnEntity(BaseConstant.FAIL, "ID为空");
        }
        WebWithdraw withdraw = this.selectByPrimaryKey(id);
        withdraw.setType(type);
        withdraw.setStatus(status);
        withdraw.setDescription(description);
        int info = this.updateByPrimaryKey(withdraw);
        if (info <= 0) {
            return new ReturnEntity(BaseConstant.FAIL, BaseConstant.DO_FAIL);
        }
        if (StringUtils.equals(status, BaseConstant.RECOVERY_WASTE_MEMBER_STATUS_THREE)) {
            // 如果是驳回，需要将还给用户
            if (StringUtils.isNotEmpty(withdraw.getMoney())) {
                WebMember webMember = webMemberService.selectByPrimaryKey(withdraw.getMemberId());
                double money = webMember.getMoney();
                if (money <= 0) {
                    return new ReturnEntity(BaseConstant.FAIL,"用户金额不足，无法退回");
                }
                webMember.setMoney(webMember.getMoney() + Double.parseDouble(withdraw.getMoney()));
                int num = webMemberService.updateByPrimaryKey(webMember);
                if (num <= 0) {
                    return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
                }

            }
        }
        if (StringUtils.equals(status, BaseConstant.RECOVERY_WASTE_MEMBER_STATUS_TWO)) {
            // 增加记录
            WebScoreRecord webScoreRecord = new WebScoreRecord();
            webScoreRecord.setId(BaseUtil.uId());
            webScoreRecord.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
            webScoreRecord.setCreateTime(new Date());
            webScoreRecord.setUpdateTime(webScoreRecord.getCreateTime());
            webScoreRecord.setScore(withdraw.getMoney());
            webScoreRecord.setExtraId(withdraw.getId());
            webScoreRecord.setRecordType("2");
            webScoreRecord.setMemberId(withdraw.getMemberId());
            webScoreRecord.setDescripts("佣金提现" + webScoreRecord.getScore() + "元");
            webScoreRecordService.insert(webScoreRecord);
        }
        return new ReturnEntity();
    }

    @Override
    public Double selectCountMoney(String memberId, String status) {
        return webWithdrawDao.selectCountMoney(memberId, status);
    }
}
